package com.hxjy.aid;

import java.io.File;
import java.net.InetAddress;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.hxjy.dao.LicenceDao;
import com.hxjy.util.ComputerMessageUtil;
import com.hxjy.util.EncryptionUtil;
import com.hxjy.util.LoadProperties;
import com.hxjy.util.SerializableUtil;
import com.libin.licence.Licence;

public class LoadLicence {
	private static Log log = LogFactory.getLog(LoadLicence.class);
	static ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
	static LicenceDao licenceDao = (LicenceDao) ac.getBean("licenceDao");
	public static void readComputerMessage(ServletContextEvent servletContextEvent){
		try {
			ServletContext application = servletContextEvent.getServletContext();
			InetAddress inetAddress = InetAddress.getLocalHost();
			String MACNum = ComputerMessageUtil.getMACAddress(inetAddress);
			
			String path = servletContextEvent.getServletContext().getRealPath("\\source\\bzhLicence.lic");
			Licence licence = (Licence) SerializableUtil.readerDataFile(new File(path));
			byte[] encryptionMess = licence.getEncryptionMess();
			String key = licenceDao.getKey(LoadProperties.getInstance().loadProperties("licence.properties").getProperty("userName"));
			byte[] decryptMess = EncryptionUtil.decryptData(encryptionMess, EncryptionUtil.hex2byte(key));
			if(key!=null&&!key.isEmpty()&&new String(decryptMess).indexOf(MACNum)>0){
				application.setAttribute("secretKey",key);
				LoadPagerConstant.loadPagerConstant(servletContextEvent);
				log.info("检查授权文件，已通过，如有其它服务，请联系山西和信基业有限科技公司为您服务！");
			}else{
				application.removeAttribute("pager");
				application.removeAttribute("licence");
				log.info("您授权失败，请联系山西和信基业有限科技公司为您服务！");
			}
		} catch (Exception e) {
			log.info("您授权失败，请联系山西和信基业有限科技公司为您服务！");
		}
		
	}
}
